package cn.conac.rc.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import cn.conac.rc.entity.VAreaInfoEntity;
import cn.conac.rc.framework.jpa.Criteria;
import cn.conac.rc.framework.jpa.Restrictions;
import cn.conac.rc.framework.service.GenericService;
import cn.conac.rc.repository.VAreaInfoRepository;
import cn.conac.rc.vo.VAreaInfoVo;

/**
 * VAreaInfoService类
 *
 * @author serviceCreator
 * @date 2017-07-14
 * @version 1.0
 */
@Service
public class VAreaInfoService extends GenericService<VAreaInfoEntity, String> {

	@Autowired
	private VAreaInfoRepository repository;
	
	/**
	 * 动态查询，分页，排序查询
	 * @param vo
	 * @return Page
	 * @throws Exception
	 */
	public Page<VAreaInfoEntity> list(VAreaInfoVo vo) throws Exception {
		try {
			Sort sort = new Sort(Direction.ASC, "code", "weight");
			Pageable pageable = new PageRequest(vo.getPage(), vo.getSize(), sort);
			Criteria<VAreaInfoEntity> dc = this.createCriteria(vo);
			return repository.findAll(dc, pageable);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 动态查询条件
	 * @param param
	 * @return Criteria
	 */
	private Criteria<VAreaInfoEntity> createCriteria(VAreaInfoVo param) {
		Criteria<VAreaInfoEntity> dc = new Criteria<VAreaInfoEntity>();
		
		if(param.getNoSelfFlag()!= null && param.getNoSelfFlag().intValue() == 1) {
			if(StringUtils.isNotBlank(param.getCode())) {
				dc.add(Restrictions.ne("code", param.getCode(), true));
			}
		} else {
			if(StringUtils.isNotBlank(param.getCode()) 
					&& !"000000000".equals(param.getCode())) {
				String serarchCode = param.getCode();
				if(param.getCode().endsWith("0000000")) {
					serarchCode = param.getCode().substring(0, 2);
				} else if(param.getCode().endsWith("0000")) {
					serarchCode = param.getCode().substring(0, 5);
				} 
	//			System.out.println("serarchCode=" + serarchCode);
				dc.add(Restrictions.QLike("code", serarchCode, true));
			}
		}
		if(StringUtils.isNotBlank(param.getName())) {
			dc.add(Restrictions.like("name", param.getName(), true));
		}
		
		if(param.getLvl() != null) {
			dc.add(Restrictions.eq("lvl", param.getLvl(), true));
		}
	
		if(param.getIsPublic() != null) {
			dc.add(Restrictions.eq("isPublic", param.getIsPublic(), true));
		}
		return dc;
	}

}
